﻿using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using MultiThumbnail;
using TestMultiThumbnail.Properties;

namespace TestMultiThumbnail
{
    public partial class MainForm : Form
    {
        private readonly ThumbnailGenerator _thumbnailGenerator = new ThumbnailGenerator();
        private int _retryCount = 0;

        public MainForm()
        {
            InitializeComponent();
            var filter = ThumbnailGenerator.AllAllowedExtensions.Aggregate("Any allowed file|", (c,n)=>c+string.Format(CultureInfo.InvariantCulture,"*.{0};", n));
            openFileDialog.Filter = ThumbnailGenerator.AllAllowedExtensions.Aggregate(filter + "|", (c,n)=>c+string.Format(CultureInfo.InvariantCulture,"{0} Files|*.{0}|", n)).TrimEnd('|');
        }

        private void btnChooseScreenshotsDir_Click(object sender, EventArgs e)
        {
            _thumbnailGenerator.ConverterSettings.ThrowExceptionOnError = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                _retryCount = 0;
                tbFilePathDir.Text = openFileDialog.FileName;
                if (pictureBox.Image != null)
                    pictureBox.Image.Dispose();
                if (_thumbnailGenerator.GenerateFor(openFileDialog.FileName))
                    UpdateGeneratedImage(openFileDialog.FileName + ".thumb.jpeg");
                else 
                    MessageBox.Show(Resources.ErrorGenerateMiniature);
            }
        }

        private void UpdateGeneratedImage(string path)
        {
            if (File.Exists(path))
            {
                if (pictureBox.Image != null)
                    pictureBox.Image.Dispose();
                pictureBox.Image = new Bitmap(path);
            }
            else if (_retryCount < 100)
            {
                _retryCount++;
                Thread.Sleep(100);
                Application.DoEvents();
                UpdateGeneratedImage(path);
            }
        }

        private void cbAllPages_CheckedChanged(object sender, EventArgs e)
        {
            ThumbnailGenerator.ExportAllPages = cbAllPages.Checked;
        }
    }
}
